package me.chenqiang.cinc.codes;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import me.chenqiang.cinc.CincCodingException;

public class ProvinceUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProvinceUtils.class);
	private static final Map<Integer, String> PROVINCE_INDEX_TO_CODE;
	private static final Map<String, Integer> PROVINCE_CODE_TO_INDEX;
	static {
		HashMap<Integer, String> i2c = new HashMap<>();
		HashMap<String, Integer> c2i = new HashMap<>();
		try(InputStream jsonFile = ProvinceUtils.class.getResourceAsStream("code_gbt_2260.json")) {
			ObjectMapper mapper = new ObjectMapper();
			ArrayNode list = (ArrayNode)mapper.readTree(new InputStreamReader(jsonFile, StandardCharsets.UTF_8));
			
			for(JsonNode prov: list) {
				int index = ((ObjectNode)prov).get("index").asInt();
				String code = ((ObjectNode)prov).get("code").asText();
				i2c.put(index, code);
				c2i.put(code, index);
			}			

			LOGGER.debug("code_gbt_2260.json文件加载完成{}项", list.size());
			
		} catch (IOException e) {
			LOGGER.error("code_gbt_2260.json文件加载或解析失败", e);
		
		} finally {
			PROVINCE_INDEX_TO_CODE = Collections.unmodifiableMap(i2c);
			PROVINCE_CODE_TO_INDEX = Collections.unmodifiableMap(c2i);
		}
	}
	
	public static long getProvinceIndex(String provinceCode) throws CincCodingException {
		Integer index = PROVINCE_CODE_TO_INDEX.get(provinceCode);		
		if(index == null) {
			throw new CincCodingException(String.format("省份代码不存在：%s", provinceCode));
		}
		return index.longValue();
	}
	
	public static String getProvinceCode(int provinceIndex)  throws CincCodingException {
		String code = PROVINCE_INDEX_TO_CODE.get(provinceIndex);
		if(code == null) {
			throw new CincCodingException(String.format("省份序号不存在：%d", provinceIndex));
		}
		return code;
	}
	
	private ProvinceUtils() {}
}
